import { ref, onMounted, onUnmounted } from 'vue'
import type { Ref } from 'vue'
import type { DeviceType } from '@/types/DeviceType'

let timer: null | number = null
let useDevice: Ref<DeviceType> = ref('pc')

function useSizeOb() {
  if (timer) clearTimeout(timer)
  timer = setTimeout(() => {
    if (window.innerWidth > 768) {
      useDevice.value = 'pc'
    } else {
      useDevice.value = 'mobile'
    }
  }, 300)
}

function useInitOb() {
  if (window.innerWidth > 768) {
    useDevice.value = 'pc'
  } else {
    useDevice.value = 'mobile'
  }
  onMounted(() => {
    window.addEventListener('resize', useSizeOb)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', useSizeOb)
    timer = null
  })
}

export { useDevice, useInitOb }
